

package CJBCompressor;
import java.io.*;
import FileBitIO.*;



public class CJBDecoder implements JBInterface{
	
	private String fileName,outputFilename;
	private char[] encodedChars = new char[MAXCHARS];
	private int distinctChars = 0;
	private int jbBits = 4;
	private long fileLen=0,outputFilelen;
	private FileOutputStream outf;
	private String gSummary;

	
	void resetCodes(){
		for(int i=0;i<MAXCHARS;i++)
		encodedChars[i] = 0;
		
		jbBits = 4;
		distinctChars = 0;
		fileLen=0;
		gSummary ="";
		}
	
	public CJBDecoder  (){
		loadFile("","");
		}
	public CJBDecoder  (String txt){
		loadFile(txt);
		}
	public CJBDecoder  (String txt,String txt2){
		loadFile(txt,txt2);
		}
		
	public void loadFile(String txt){
		fileName = txt;
		outputFilename = stripExtension(txt,strExtension);
		resetCodes();
		}
	public void loadFile(String txt,String txt2){
		fileName = txt;
		outputFilename = txt2;
		resetCodes();
		}
		
	String stripExtension(String ff,String ext){
		ff = ff.toLowerCase();
		if(ff.endsWith(ext.toLowerCase())){
			return ff.substring(0,ff.length()-ext.length());
			}
		return "_" + ff;
		}

	public boolean decodeFile() throws Exception{
		
		
		if(fileName.length() == 0) return false;
		
		CFileBitReader fin = new CFileBitReader(fileName);
		fileLen = fin.available();

		String buf;
		buf = fin.getBytes(jbcSignature.length());
		
		if(!buf.equals(jbcSignature)) return false;
		outputFilelen = Long.parseLong(fin.getBits(32),2);
		distinctChars = Integer.parseInt(fin.getBits(8),2);
		gSummary  += ("Compressed File Size : "+ fileLen + "\n");
		gSummary  += ("Original   File Size : "+ outputFilelen + "\n");
		gSummary  += ("Encoded   Chars     : "+ distinctChars + "\n");
		
		
		if(distinctChars <= 8) jbBits = 3;
		if(distinctChars <= 4) jbBits = 2;
		if(distinctChars <= 2) jbBits = 1;
		
		for(int i=0;i<distinctChars;i++){
			encodedChars[i] = (char)Integer.parseInt(fin.getBits(8),2);
			//System.out.println(encodedChars[i]);
			}
		
		try{
		
		outf = new FileOutputStream(outputFilename);
		long i = 0;
		
		int ch;
		int bool;
		
		while(i < outputFilelen){
			bool = Integer.parseInt(fin.getBits(1),2);
			
			if(bool == 0){ //not compressed
			ch = Integer.parseInt(fin.getBits(8),2);
			outf.write(ch);
			}else{ //compressed
			ch = Integer.parseInt(fin.getBits(jbBits),2);
			outf.write(encodedChars[ch]);
			}
			i++;
			}
		
		outf.close();
		return true;
		
		}catch(Exception e){
			throw e;
		}
		

		}


	String leftPadder(String txt,int n){
		while(txt.length() < n )
			txt =  "0" + txt;
		return txt;
		}
	
	String rightPadder(String txt,int n){
		while(txt.length() < n )
			txt += "0";
		return txt;
		}
		
	public String getSummary(){
		return gSummary;
		}

	
	}


